/*
 * @(#)Table.java	1.0 2000/12/19
 *
 * Copyright 2000 Thomas Barnekow. All Rights Reserved.
 *
 * This software is the proprietary information of Thomas Barnekow.
 * Use is subject to license terms.
 */

package tb.provider.jdbc;

import java.sql.*;
import java.util.*;

import tb.provider.*;
import tb.util.*;

/**
 * Table metadata.
 *
 * @author Thomas Barnekow
 * @version 1.0
 */
public class Table extends AbstractCompoundMetaObject implements NamedObject {

  public static String TYPE_TABLE = "TABLE";
  public static String TYPE_VIEW = "VIEW";

  private String m_type;
  private String m_remarks;
  private QualifiedName m_qn;

  Table(String name, String type, String remarks, Schema schema) {
    super(name, schema);
    m_type = type;
    m_remarks = remarks;
    m_qn = new QualifiedName(schema.getQualifiedName(), name);
  }

  /*
   * AbstractCompoundMetaObject operations
   */

  protected Collection createElementCollection() throws SQLException {
    List columns = new ArrayList();

    String schemaName = getContainer().getId().toString().toUpperCase();
    String tableName = getId().toString().toUpperCase();

    ResultSet result = getConnection().getMetaData().getColumns(
      null, schemaName, tableName, "%");

    while (result.next()) {
      Column column = new Column(result.getString(4).toLowerCase(), this);
			column.setDataType((int) result.getShort(5));
			column.setTypeName(result.getString(6).toUpperCase());
      column.setColumnSize(result.getInt(7));
      column.setDecimalDigits(result.getInt(9));
      column.setNullable(result.getInt(11));
      column.setRemarks(result.getString(12));
      column.setDefaultValue(result.getString(13));

      columns.add(column);
    }
    result.close();

    // Done
    return Collections.unmodifiableCollection(columns);
  }

  public MetaObject get(Comparable id) {
    return super.get(id.toString().toLowerCase());
  }

  /*
   * NamedObject operations
   */

  public QualifiedName getQualifiedName() {
    return m_qn;
  }

  /*
   * This class' operations
   */

  public final Connection getConnection() {
    return ((Schema) getContainer()).getConnection();
  }

  public final String getType() {
    return m_type;
  }

  public final String getRemarks() {
    return m_remarks;
  }
}